package com.daafan.minilib.activity;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.daafan.minilib.R;
import com.daafan.minilib.data.BookData;
import com.daafan.minilib.data.BookList;
import com.daafan.minilib.data.Library;
import com.daafan.minilib.data.Skin;
import com.daafan.minilib.data.VideoLesson;
import com.daafan.minilib.http.EBookHttp;
import com.daafan.minilib.http.HttpHandler;
import com.google.gson.Gson;
import com.google.zxing.Result;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.umeng.update.UmengUpdateAgent;
import com.zijunlin.Zxing.Demo.CaptureActivity;

public class HomeActivity extends BaseActivity implements OnClickListener {

	ImageView	img_bg;

	ImageView	btn_ebook;
	ImageView	btn_eMagazine;
	ImageView	btn_temp;
	ImageView	btn_rock;
	ImageView	btn_course;

	Button		btn_setting;
	Button		btn_skin;
	ImageView	img_qcode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);

		// UmengUpdateAgent.setUpdateCheckConfig(false);
		UmengUpdateAgent.update(this);

		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();

		// 设定的皮肤
		List<Skin> list = db.findAll(Skin.class);
		Skin skin = null;
		if (list != null && list.size() > 0)
			skin = list.get(0);

		if (skin != null || (skin != null && skin.url != null && !skin.url.equals(""))) {
			img_bg = (ImageView) findViewById(R.id.img_home_bg);

			DisplayImageOptions options = new DisplayImageOptions.Builder().cloneFrom(getApp().getDisplayOptions())
					.showImageForEmptyUri(R.drawable.h_bg).showImageOnFail(R.drawable.h_bg)

					.build();
			mImageLoader.displayImage(skin.url, img_bg, options);
		}
	}

	private void initView() {

		btn_ebook = (ImageView) findViewById(R.id.btn_home_eBooks);
		btn_ebook.setOnClickListener(this);

		btn_eMagazine = (ImageView) findViewById(R.id.btn_home_eMagazine);
		btn_eMagazine.setOnClickListener(this);

		btn_temp = (ImageView) findViewById(R.id.btn_home_temp);
		btn_temp.setOnClickListener(this);

		btn_rock = (ImageView) findViewById(R.id.btn_home_rock);
		btn_rock.setOnClickListener(this);

		btn_course = (ImageView) findViewById(R.id.btn_home_course);
		btn_course.setOnClickListener(this);

		img_qcode = (ImageView) findViewById(R.id.img_home_bottom_qcode);
		img_qcode.setOnClickListener(this);

		btn_setting = (Button) findViewById(R.id.btn_home_bottom_setting);
		btn_setting.setOnClickListener(this);

		btn_skin = (Button) findViewById(R.id.btn_home_bottom_skin);
		btn_skin.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		Intent intent = null;

		switch (v.getId()) {
			case R.id.btn_home_eBooks:

				intent = new Intent(this, BookListActivity.class);
				startActivity(intent);

				break;
			case R.id.btn_home_eMagazine:

				intent = new Intent(this, EJournalActivity.class);
				startActivity(intent);

				break;
			case R.id.btn_home_temp:
				intent = new Intent(this, TempBooksActivity.class);
				startActivity(intent);

				break;

			case R.id.btn_home_course:
				intent = new Intent(this, VideosActivity.class);
				startActivity(intent);

				break;
			case R.id.btn_home_rock:
				intent = new Intent(this, ShakeActivity.class);
				startActivity(intent);

				break;
			case R.id.img_home_bottom_qcode:

				CaptureActivity.setListener(new MyCaptureListener());
				intent = new Intent(this, CaptureActivity.class);
				startActivity(intent);

				break;
			case R.id.btn_home_bottom_setting:
				intent = new Intent(this, SettingActivity.class);
				startActivity(intent);

				break;
			case R.id.btn_home_bottom_skin:
				intent = new Intent(this, SkinActivity.class);
				startActivity(intent);

				break;
			default:
				break;
		}
	}

	private static final long	VIBRATE_DURATION	= 200L;

	class MyCaptureListener implements CaptureActivity.CaptureListener {

		@Override
		public boolean handleDecode(Result rawResult, Bitmap barcode, final Activity activity) {

			showProgressBar();

			// 按back键让Dialog消失，可以重新扫描二维码
			final DialogInterface.OnDismissListener dismissListener = new OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface dialog) {
					if (activity instanceof CaptureActivity) {
						((CaptureActivity) activity).restartPreviewAfterDelay(1000L);
					}
				}
			};

			Vibrator vibrator = (Vibrator) activity.getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);

			// 分析返回结果
			String resultStr = rawResult.getText(); // 例如,BOOK|00:92:d4:05:1f:5d|535478444fd70614a845bcb2|肩周炎
			String[] parts = resultStr.split("\\|");

			final String imei = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId();

			if (parts != null) { // [﻿BOOK, 88888888, 52e4b7bf4fd7061d2c638f3b, 闯关东]
				final String code = parts[1];

				if (parts[0].contains("BOOK")) { // 电子书 ﻿BOOK|88888888|52e4b7bf4fd7061d2c638f3b|闯关东

					String id = parts[2];

					EBookHttp http = new EBookHttp();
					http.setParams(id, imei, code);
					http.req(new HttpHandler(activity) {

						@Override
						public void onSuccess(String t) {
							final BookData book = new Gson().fromJson(t, BookData.class);
							book.pdfurl = imei(book.pdfurl, code, imei);

							showConfirmDialog(activity, "电子书下载", "是否确认下载" + book.getBookname(), new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									// 向电子书加入任务
									BookList bookList = new BookList();
									bookList.restore(activity);
									bookList.add(activity, book);

									Intent intent = new Intent(activity, BookListActivity.class);
									intent.putExtra(BookListActivity.BOOK_ID, book.getBookid());
									startActivity(intent);

									activity.finish();
								}
							}, dismissListener);
						}
					});
				} else if (parts[0].contains("MAGAZINE")) { // 电子杂志

					String id = parts[2];
					final String url = parts[3];
					showConfirmDialog(activity, "电子杂志", "是否确认下载?", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(activity, EJournalActivity.class);
							intent.putExtra(EJournalActivity.EJOURNAL_URL, imei(url, code, imei));
							startActivity(intent);

							activity.finish();
						}
					}, dismissListener);
				} else if (parts[0].contains("LIBRARY")) { // 临时书架

					final Library library = new Library();
					library.setLid(Integer.valueOf(parts[2]));
					library.setName(parts[3]);
					library.setUrl(imei(parts[4], code, imei));

					showConfirmDialog(activity, "临时书架", "是否收藏" + library.getName() + " 到临时书架 ", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 储存图书
							List<Library> list = db.findAllByWhere(Library.class, "lid=" + library.lid);

							// 没有相同的书
							if (list.size() == 0) {
								db.save(library);
							} else {
								Toast.makeText(mContext, "你已经收藏过该书了", 0).show();

								db.deleteByWhere(Library.class, "lid=" + library.lid);
								db.save(library);
							}

							Intent intent = new Intent(activity, TempBooksActivity.class);
							startActivity(intent);

							activity.finish();
						}
					}, dismissListener);

				} else if (parts[0].contains("VIDEO")) { // 视频课程

					final VideoLesson video = new VideoLesson();
					video.setVid(parts[2]);
					video.setName(parts[3]);
					video.setCategory(parts[4]);
					video.setUrl(imei(parts[5], code, imei));

					showConfirmDialog(activity, "视频课程", "是否收藏 " + video.getName() + "到视频课程", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							// 保存视频课程
							List<VideoLesson> list = db.findAllByWhere(VideoLesson.class, "vid=\"" + video.vid + "\"");

							// 没有相同的书
							if (list.size() == 0)
								db.save(video);
							else {
								Toast.makeText(mContext, "你已经收藏过该课程了", 0).show();

								db.deleteByWhere(VideoLesson.class, "vid=\"" + video.vid + "\"");
								db.save(video);
							}

							Intent intent = new Intent(activity, VideosActivity.class);
							startActivity(intent);

							activity.finish();
						}
					}, dismissListener);
				}
			}

			return true;
		}

	}

	private String imei(String url, String code, String imei) {
		String r_url = url;

		if (url.contains("?")) {
			r_url = url + "&code=" + code + "&imei=" + imei;
		} else {
			r_url = url + "?code=" + code + "&imei=" + imei;
		}

		return r_url;
	}

	public AlertDialog.Builder	mAlertDialogBuilder;

	public void showConfirmDialog(Context context, String title, String msg, DialogInterface.OnClickListener listener,
			DialogInterface.OnDismissListener dismissListener) {
		dismissProgressBar();

		try {
			mAlertDialogBuilder = new Builder(context);
			mAlertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert).setTitle(title).setMessage(msg)
					.setPositiveButton("确定", listener).setNegativeButton("取消", null);
			mAlertDialog = mAlertDialogBuilder.create();
			mAlertDialog.setCancelable(true);
			mAlertDialog.setCanceledOnTouchOutside(true);
			mAlertDialog.setOnDismissListener(dismissListener);
			mAlertDialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
